package service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.aop.Aop;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

import enums.RoleType;
import model.Role;
import model.RoleMenu;
import model.User;
import model.UserRole;

public class RoleService extends BaseService {

	static MenuRoleService menuRoleService = Aop.get(MenuRoleService.class);

	public Ret save(Role role , User user) {
		Long id = role.getId();
		if (role.isRepeatName()) {
			return fail("角色名称已存在");
		}
		if(id == null) {
			role.save();
		}else {
			role.update();
		}
		
		menuRoleService.save(role.getId(), role.getMenuIds() , user );
		
		CacheKit.removeAll("menuList");
		
		return Ret.ok();
	}

	public Ret delete(Long id) {
		long count = UserRole.dao.CountByRoleId(id);
		if(count > 0) {
			return fail("当前角色已有用户使用，请勿删除");
		}
		RoleMenu.dao.deleteByRoleId(id);
		return Role.dao.deleteById(id) ? Ret.ok() : fail("删除失败") ;
	}
	
	public List<Record> findAll() {
		List<Record> roles = new ArrayList<Record>();
		List<Role> list = Role.dao.findAll();
		for (Role role : list) {
			Record record = role.toRecord() ;
			record.set("typeName", RoleType.getTitleByValue(record, "type"));
			roles.add(record);
		}
		return roles ;
	}
	
}
